package cn.itsource.basic.util;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;

/**
 * 短信发送接口
 */
public class SmsUtil {

    //uid
    private static final String UID = "xllyuan";
    //key
    private static final String KEY = "d41d8cd98f00b204e980";


    /**
     * 发送短信信息
     * @param phones 发给哪些手机号，多个用“，”隔开
     * @param msg 短信内容
     */
    public static void sendMsg(String phones,String msg){
        PostMethod post = null;
        try {
            //创建发送请求客户端
            HttpClient client = new HttpClient();

            //post请求
            post = new PostMethod("http://utf8.api.smschinese.cn");
            post.addRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=utf8");//在头文件中设置转码
            NameValuePair[] data ={ new NameValuePair("Uid", UID),
                    new NameValuePair("Key", KEY),
                    new NameValuePair("smsMob",phones)
                    ,new NameValuePair("smsText",msg)};
            post.setRequestBody(data);

            //发请求
            client.executeMethod(post);
            Header[] headers = post.getResponseHeaders();
            //获取状态码 200 404 500
            int statusCode = post.getStatusCode();
            System.out.println("statusCode:"+statusCode);
//            for(Header h : headers)
//            {
//                System.out.println(h.toString());
//            }
            String result = new String(post.getResponseBodyAsString().getBytes("utf8"));
            System.out.println(result); //打印返回消息状态

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (post != null) {
                post.releaseConnection();
            }
        }
    }
}
